package com.chuanyang.driverh.mainmy;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.GoodOwnerInfoActivity;
import com.chuanyang.driverh.mainorder.adapter.WayBillGoodInfoAdapter;
import com.chuanyang.driverh.mainorder.adapter.WayBillPassPointAdapter;
import com.chuanyang.driverh.responseresult.DriverWayBillData;
import com.chuanyang.driverh.responseresult.WayBillDetailResult;
import com.chuanyang.driverh.responseresult.WaybillDetailsData;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.TimeUtils;
import com.chuanyang.driverh.utils.eventbus.SubscribeEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.CustomMeasureHeightListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class HisWayBillDetailActivity extends BaseTitleActivity {
    private ImageView iv_peopleicon;
    private RatingBar ratingBar;
    private TextView tv_peoplename;
    private TextView tv_phone;
    private TextView tv_waybillcode;
    private TextView tv_account;
    private TextView tv_act;
    private CustomMeasureHeightListView lv_varpalaces;
    private CustomMeasureHeightListView lv_orderlist;
    private HashMap params;
    private DriverWayBillData.DataBean waybill;
    private ArrayList<WaybillDetailsData.PassPointsBean> passpointlist;
    public int index = 0;
    private ScrollView sc_waybilldetailinfo;
    private TextView tv_orderdate;
    private ArrayList<WaybillDetailsData.PassPointsBean> fillpointlist;
    private WaybillDetailsData.PassPointsBean startPoint;
    private WaybillDetailsData.PassPointsBean endPoint;
    private WayBillPassPointAdapter passPointAdapter;
    private WaybillDetailsData data;
    private LinearLayout ll_waybilldetail_div;
    private TextView tv_waybillinfo_dingyue;
    private LinearLayout ll_waybillinfo_act;
    private String waybillId;
    private double   sumweight;
    private double   sumnum;
    private LinearLayout ll_waybillinfodetail_cartimediv;
    private TextView tv_waybillinfodetail_deliverydate;
    private TextView tv_waybillinfodetail_picuupdate;
    private LinearLayout ll_waybillinfodetail_shiptimediv;
    private TextView tv_waybillinfodetail_loaddatebeg;
    private TextView tv_waybillinfodetail_loaddateend;
    private TextView tv_waybillinfodetail_stevedoreDaybeg;
    private TextView tv_waybillinfodetail_stevedoreDayend;
    private TextView tv_waybillinfodetail_taskname;
    private TextView tv_waybillinfodetail_demurrage;
    private TextView tv_waybillinfo_remark;
    //    private TextView tv_waybillinfodetail_outnum;
    private TextView tv_waybillinfodetail_count;
    private TextView tv_waybillinfodetail_load;
    private TextView tv_waybilldetail_amount;
    private TextView tv_waybilldetail_price;
//    private LinearLayout ll_oredrinfodetail_account;
    private TextView tv_waybillinfodetail_tradetype;
    private ImageView iv_waybillinfo_phoneicon;
private Dialog dialog;
    @Override
    protected int getContentResId() {
        return R.layout.order_act_waybilldetailinfo;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        showActivityLoading();
        ll_waybilldetail_div = (LinearLayout) findViewById(R.id.ll_waybilldetail_div);
        sc_waybilldetailinfo = (ScrollView) findViewById(R.id.sc_waybilldetailinfo);
        iv_peopleicon = (ImageView) findViewById(R.id.iv_waybillinfo_peopleicon);
        ratingBar = (RatingBar) findViewById(R.id.rb_waybillinfo_stars);
        tv_peoplename = (TextView) findViewById(R.id.tv_waybillinfo_peoplename);
        tv_waybillinfo_remark = (TextView) findViewById(R.id.tv_waybillinfo_remark);
        tv_waybillinfo_dingyue = (TextView) findViewById(R.id.tv_waybillinfo_dingyue);//订阅
        tv_phone = (TextView) findViewById(R.id.tv_waybillinfo_phone);
        iv_waybillinfo_phoneicon = (ImageView) findViewById(R.id.iv_dial);
        tv_orderdate = (TextView) findViewById(R.id.tv_waybillinfo_orderdate);//货单时间
//        ll_oredrinfodetail_account = (LinearLayout) findViewById(R.id.ll_oredrinfodetail_account);
        tv_waybillcode = (TextView) findViewById(R.id.tv_waybillinfodetail_waybillid);//运单号
//        tv_waybillinfodetail_outnum = (TextView) findViewById(R.id.tv_waybillinfodetail_outnum);//发货通知单号
        tv_waybillinfodetail_tradetype = (TextView) findViewById(R.id.tv_waybillinfodetail_tradetype);//贸易类型
        //数量
        tv_waybillinfodetail_count = (TextView) findViewById(R.id.tv_waybillinfodetail_count);
        //载重
        tv_waybillinfodetail_load = (TextView) findViewById(R.id.tv_waybillinfodetail_load);
        //金额
        tv_waybilldetail_amount = (TextView) findViewById(R.id.tv_waybilldetail_amount);
        //单价
        tv_waybilldetail_price = (TextView) findViewById(R.id.tv_waybilldetail_price);
        //车辆运单时显示的界面
        ll_waybillinfodetail_cartimediv = (LinearLayout) findViewById(R.id.ll_waybillinfodetail_cartimediv);
        tv_waybillinfodetail_deliverydate = (TextView) findViewById(R.id.tv_waybillinfodetail_deliverydate);//发货时间
        tv_waybillinfodetail_picuupdate = (TextView) findViewById(R.id.tv_waybillinfodetail_picuupdate);//取货时间
        tv_waybillinfodetail_taskname = (TextView) findViewById(R.id.tv_waybillinfodetail_taskname);//任务名称有则显示 没有则不显示

        //-----------------------

        //船只运单时显示的界面
        ll_waybillinfodetail_shiptimediv = (LinearLayout) findViewById(R.id.ll_waybillinfodetail_shiptimediv);
        tv_waybillinfodetail_loaddatebeg = (TextView) findViewById(R.id.tv_waybillinfodetail_loaddatebeg);
        tv_waybillinfodetail_loaddateend = (TextView) findViewById(R.id.tv_waybillinfodetail_loaddateend);
        tv_waybillinfodetail_stevedoreDaybeg = (TextView) findViewById(R.id.tv_waybillinfodetail_stevedoreDaybeg);
        tv_waybillinfodetail_stevedoreDayend = (TextView) findViewById(R.id.tv_waybillinfodetail_stevedoreDayend);
        //滞期费
        tv_waybillinfodetail_demurrage = (TextView) findViewById(R.id.tv_waybillinfodetail_demurrage);

        //-----------------------
//        tv_act = (TextView) findViewById(R.id.tv_waybillinfo_act);//最底部的按钮
        lv_varpalaces = (CustomMeasureHeightListView) findViewById(R.id.ll_waybillinfo_varpalace);
        lv_orderlist = (CustomMeasureHeightListView) findViewById(R.id.ll_waybillinfo_orderlist);
        ll_waybillinfo_act = (LinearLayout) findViewById(R.id.ll_waybillinfo_act);        //底部两个按钮所在布局
        ll_waybillinfo_act.setVisibility(View.GONE);
//        tv_waybillinfo_act2 = (TextView) findViewById(R.id.tv_waybillinfo_act2);//底部的第二个按钮




    }

    @Override
    protected void initData() {
        setBackImg();
        getTitleTextView().setText("历史运单");
        Intent intent = getIntent();
        waybillId = intent.getStringExtra("WaybillId");
        requsetData();
    }

    @Override
    protected void initListener() {
        ll_waybilldetail_div.setOnClickListener(this);
        iv_waybillinfo_phoneicon.setOnClickListener(this);
    }


    private void requsetData() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillId", waybillId);
        MyHttpUtil.selectWaybillMsg(activityContext,params, new MyCallback<WayBillDetailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(WayBillDetailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    data = result.getData();
                    fillView(data);
                    hideActivityLoading();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });

    }
    public void onEventMainThread(SubscribeEvent event) {
        if (event.isChangeSubscribed()) {
            requsetData();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_waybilldetail_div:
                if (data != null) {
                    ActivityUtil.startActivity(activityContext,new Intent(activityContext,GoodOwnerInfoActivity.class).putExtra("data",data));
                }
                break;

            case R.id.iv_dial:
                DialogUtil.dial(activityContext,data.getPhone());
                /*if (data!=null && data.getPhone() != null) {
                    dialog= DialogUtil.myDialog(activityContext, "拨打电话", "取消", "确定", "确定拨打电话：" + data.getPhone(), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()){
                                case R.id.dialog_btn_left:
                                    break;
                                case R.id.dialog_btn_right:
                                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + data.getPhone()));
                                    try {
                                        if (PermissoinUtil.checkAndRequestPermission(activityContext, android.Manifest.permission.CALL_PHONE, "请给应用添加拨打电话的权限！"))
                                            startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    break;
                            }
                            dialog.cancel();
                        }
                    });
                }*/
                break;
        }
    }

    private void fillView(WaybillDetailsData data) {
        BitmapUtil.showImgForNetPath(data.getUserImage(),iv_peopleicon);
        ratingBar.setRating(data.getStar());
        tv_phone.setText(data.getPhone());
        tv_orderdate.setText(data.getCreatetime() + "");
        tv_waybillcode.setText(data.getWaybillNo());
        if(TextUtils.isEmpty(data.getAssignment()))
        {
            tv_waybillinfodetail_taskname.setVisibility(View.GONE);
        }
        else
        {
            tv_waybillinfodetail_taskname.setText("任务名称：    "+data.getAssignment());
        }
        if(data.getCurrency()==2)
        {
            tv_waybillinfodetail_tradetype.setVisibility(View.VISIBLE);
        }
        else {
            tv_waybillinfodetail_tradetype.setVisibility(View.GONE);

        }
        if (data.getTransPortWay() == 1)//车
        {
            tv_waybillinfodetail_deliverydate.setText(TimeUtils.getStandardTime(data.getOrder_startime()));
            tv_waybillinfodetail_picuupdate.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            ll_waybillinfodetail_cartimediv.setVisibility(View.VISIBLE);
            ll_waybillinfodetail_shiptimediv.setVisibility(View.GONE);

        } else if (data.getTransPortWay() == 2)//船
        {
            tv_waybillinfodetail_loaddatebeg.setText(data.getLoadDate());
            tv_waybillinfodetail_loaddateend.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            tv_waybillinfodetail_stevedoreDaybeg.setText(data.getStevedoreDay());
            tv_waybillinfodetail_stevedoreDayend.setText(data.getFq());

            tv_waybillinfodetail_demurrage.setText(data.getDemurrage()+data.getUnit()+"/天/吨");
            ll_waybillinfodetail_cartimediv.setVisibility(View.GONE);
            ll_waybillinfodetail_shiptimediv.setVisibility(View.VISIBLE);

        }
//        if(!TextUtils.isEmpty(data.getWaybillDetailMsgList().get(0).getNoticeNo()))//发货通知单 有则显示
//        {
//            tv_waybillinfodetail_outnum.setVisibility(View.VISIBLE);
//            tv_waybillinfodetail_outnum.setText("发货通知单：    "+data.getWaybillDetailMsgList().get(0).getNoticeNo());
//
//        }
//        else {
//            tv_waybillinfodetail_outnum.setVisibility(View.GONE);
//        }
        if (!TextUtils.isEmpty(data.getUsername())) {
            tv_peoplename.setText(data.getUsername());

        } else {
            tv_peoplename.setText("---");

        }
        if (!TextUtils.isEmpty(data.getRemark())) {
            tv_waybillinfo_remark.setText(data.getRemark());
        } else {
            tv_waybillinfo_remark.setText("");

        }
        if (data.getSubscriptionStatus() == 1) {
            tv_waybillinfo_dingyue.setText("已订阅");
        } else if (data.getSubscriptionStatus() == 2) {
            tv_waybillinfo_dingyue.setText("未订阅");
        }
        //需要传入到适配器的数据
        fillpointlist = new ArrayList();
        passpointlist = new ArrayList();
        try{
            for(WaybillDetailsData.WaybillDetailMsgListBean   bean:data.getWaybillDetailMsgList())
            {
                double weight=Double.parseDouble(bean.getGoodsWeight());
                double num=Double.parseDouble(bean.getGoodsNum());
                sumweight=sumweight+weight;
                sumnum=sumnum+num;


            }
            tv_waybillinfodetail_load.setText(sumweight+"t");
            tv_waybillinfodetail_count.setText(sumnum+"");
            tv_waybilldetail_amount.setText("金额："+String.format("%.2f",sumweight*(data.getPrice()))+data.getUnit());
            tv_waybilldetail_price.setText("单价："+data.getPrice()+data.getUnit()+"/t");
        }catch (Exception e)
        {
//            ll_oredrinfodetail_account.setVisibility(View.GONE);
        }
        for (WaybillDetailsData.PassPointsBean passPointsBean : data.getPassPoints()) {
            if (passPointsBean.getPointType().equals("s")) {
                startPoint = passPointsBean;
            } else if (passPointsBean.getPointType().equals("p")) {
                passpointlist.add(passPointsBean);
            } else {
                endPoint = passPointsBean;

            }
        }
        WayBillGoodInfoAdapter orderInfoAdapter = new WayBillGoodInfoAdapter(this, data.getWaybillDetailMsgList());
        lv_orderlist.setAdapter(orderInfoAdapter);
        fillpointlist.clear();
        fillpointlist.add(startPoint);
        lv_varpalaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (passpointlist.size() > 0) {
                    if (0 < position && position < passpointlist.size() + 1) {
                        fillpointlist.clear();
                        fillpointlist.add(startPoint);
                        if ((index++) % 2 == 1) {
                            fillpointlist.addAll(passpointlist);
                            fillpointlist.add(endPoint);

                        } else {
                            fillpointlist.add(passpointlist.get(0));
                            fillpointlist.add(endPoint);

                        }

                        passPointAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
        if (passpointlist.size() > 0) {
            fillpointlist.add(passpointlist.get(0));

        }
        fillpointlist.add(endPoint);
        passPointAdapter = new WayBillPassPointAdapter(this, fillpointlist);
        //设置数据适配器
        lv_varpalaces.setAdapter(passPointAdapter);


        if (data.getWaybillStatus() < 0) {//运单全是个人的 且不存在状态1
            ll_waybillinfo_act.setVisibility(View.GONE);

        }

        //滚动到原点  注意这两个方法需要一起使用 前者打断动画，后者实现移动
        sc_waybilldetailinfo.scrollTo(0, 0);
        sc_waybilldetailinfo.smoothScrollTo(0, 0);
    }



}
